app.controller('BusRouteOrderByCtrl', function ($scope, $modalInstance, param, ajax, $timeout, toaster) {

	$scope.param = param;
	if ($scope.param.data == null) $scope.param.data = {};
	$scope.list = $scope.param.list;
	$scope.param.start.distance = 0;
	$scope.param.start.duration = 0;
	$scope.param.termina.distance = 0;
	$scope.param.termina.duration = $scope.param.termina.duration || 0;

	$scope.destination = function (station) {
		station.destination = !(station.destination || false);
	};

	$scope.ok = function () {
		$scope.ids = [];
		if ($scope.myForm.$valid) {
			var ul = angular.element(document).find("li.list-group-item");
			$scope.ids.push({
				stationId: $scope.param.start.id,
				distance: 0,
				destination: false,
				duration: $scope.param.start.duration * 60,
				idx: 1,
				lastIdx: $scope.list.length + 2,
				type: 1
			});
			if ($scope.list.length > 0) {
				var count = 1;
				for (var idx in $scope.list) {
					var li = angular.element(ul[idx]);
					var station = angular.fromJson(li.attr("value"));
					for (var i = 0; i < $scope.param.list.length; i++) {
						if ($scope.param.list[i].id == station.id) {
							++count;
							$scope.ids.push({
								stationId: $scope.param.list[i].id,
								distance: 0,
								destination: station.destination == undefined ? false : station.destination,
								duration: station.duration * 60,
								idx: count,
								lastIdx: $scope.list.length + 2,
								type: 2
							});
						}
					}
				}
			}
			$scope.ids.push({
				stationId: $scope.param.termina.id,
				distance: 0,
				destination: true,
				duration: $scope.param.termina.duration * 60,
				idx: $scope.list.length + 2,
				lastIdx: $scope.list.length + 2,
				type: 3
			});
			toaster.pop('success', '成功', '站点排序成功。');
			$modalInstance.close($scope.ids);
		}
	};

	$scope.cancel = function () {
		$modalInstance.dismiss('cancel');
	};
})